<script setup>
  import { BASE_URL } from '@/utils/request'
  import { ElMessage } from 'element-plus'
  defineProps({
    imageUrl: {
      type: String,
      default: ''
    }
  })
  const emit = defineEmits(['update:imageUrl'])

  const handleAvatarSuccess = (response) => {
    if (response.code !== 200) return ElMessage.error(response.msg || '上传失败')
    emit('update:imageUrl', response.data[0])
  }

  const beforeAvatarUpload = (rawFile) => {
    if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png') {
      ElMessage.error('图片只能是jpg、png格式')
      return false
    } else if (rawFile.size / 1024 / 1024 > 0.5) {
      ElMessage.error('图片大小不能超过500kb!')
      return false
    }
    return true
  }
</script>

<template>
  <el-upload :action="BASE_URL + '/imageUpload'" name="file" :show-file-list="false" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
    <div class="upload">
      <img v-if="imageUrl" :src="imageUrl" class="avatar" />
      <template v-else>
        <el-icon><plus /></el-icon>
        <span>建议上传大小不超过500kb, 宽为900px, 高为1280px</span>
      </template>
    </div>
  </el-upload>
</template>

<style scoped lang="scss">
  .upload {
    border: 1px dashed rgba(0, 0, 0, 0.3);
    color: #0000004d;
    width: 300px;
    height: 300px;
    border-radius: 4px;
    overflow: hidden;

    display: flex;
    align-items: center;
    justify-content: center;
    flex-direction: column;
    text-align: center;
    cursor: pointer;
    img {
      width: 100%;
      height: 100%;
      object-fit: cover;
    }
    .el-icon {
      font-size: 40px;
      margin-bottom: 10px;
    }
  }
</style>
